package com.lianzhihui.romeex.ui.mianfragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.zxing.client.android.Intents;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.callback.Callback;
import com.hyphenate.helpdesk.easeui.util.IntentBuilder;
import com.lianzhihui.romeex.MyApplication;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.SaveAddressInfo;
import com.lianzhihui.romeex.bean.UserInfoBean;
import com.lianzhihui.romeex.bean.UserRegisterKFBean;
import com.lianzhihui.romeex.bean.user.WalletInfo;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.mvp.presenter.MeFragmentPresnterImp;
import com.lianzhihui.romeex.mvp.view.MeFragmentView;
import com.lianzhihui.romeex.ui.account.ImportWalletActivity;
import com.lianzhihui.romeex.ui.account.WalletManagerActivity;
import com.lianzhihui.romeex.ui.base.BaseFragment;
import com.lianzhihui.romeex.ui.me.AboutUsActivity;
import com.lianzhihui.romeex.ui.me.AddAddressActivity;
import com.lianzhihui.romeex.ui.me.AddressActivity;
import com.lianzhihui.romeex.ui.me.BindRomeexActivity;
import com.lianzhihui.romeex.ui.me.InvitationActivity;
import com.lianzhihui.romeex.ui.me.MessageActivity;
import com.lianzhihui.romeex.ui.me.SecurityCenterActivity;
import com.lianzhihui.romeex.ui.me.SettingActivity;
import com.lianzhihui.romeex.ui.orepool.MyTeamActivity;
import com.lianzhihui.romeex.ui.qrcode.ScanActivity;
import com.lianzhihui.romeex.ui.wallet.ZhuanZhangActivity;
import com.lianzhihui.romeex.utils.GsonUtil;
import com.lianzhihui.romeex.utils.ImagesUtil;
import com.lianzhihui.romeex.utils.IntentUtils;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.QrUtils.QRUtils;
import com.lianzhihui.romeex.utils.StatusBarUtil;
import com.lianzhihui.romeex.utils.StringTool;
import com.lianzhihui.romeex.utils.UserUtils;

import java.text.MessageFormat;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.lianzhihui.romeex.utils.StringTool.addHead;

/**
 * @ProjectName: romeex
 * @Package: com.lianzhihui.romeex.ui.ecological
 * @ClassName: EcologicalFragment
 * @Description: java类作用描述
 * @Author: zhanghong
 * @CreateDate: 2020/10/26 15:13
 * @UpdateUser: 更新者：
 * @UpdateDate: 2020/10/26 15:13
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class MeFragment extends BaseFragment implements MeFragmentView {
    @BindView(R.id.status_bar_id)
    View statusBarId;
    //    @BindView(R.id.message_notice_layout)
//    FrameLayout messageNoticeLayout;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_address)
    TextView userAddress;
    @BindView(R.id.user_level)
    ImageView userLevel;
    @BindView(R.id.rl_manage_address)
    LinearLayout rlManageAddress;
    @BindView(R.id.security_center_layout)
    RelativeLayout securityCenterLayout;
    @BindView(R.id.address_layout)
    RelativeLayout addressLayout;
    @BindView(R.id.customer_server)
    RelativeLayout customerServer;
    @BindView(R.id.about_us_layout)
    RelativeLayout aboutUsLayout;
    @BindView(R.id.setting_layout)
    RelativeLayout settingLayout;
    @BindView(R.id.tv_scan)
    ImageView tvScan;
    @BindView(R.id.icon_kz)
    ImageView icon_kz;
    @BindView(R.id.qr_code_inv)
    ImageView qr_code_inv;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.tv_message_note_dot)
    TextView tvMessageNoteDot;
    @BindView(R.id.tv_inv_friend)
    TextView tvInvFriend;
    @BindView(R.id.tv_my_team)
    TextView tvMyTeam;
    @BindView(R.id.tv_bind_romeex)
    TextView tvBindRomeex;
    @BindView(R.id.user_inv_code)
    TextView user_inv_code;
    @BindView(R.id.layout_inv)
    RelativeLayout layoutInv;
    @BindView(R.id.main_wallet_oc_lin_main)
    RelativeLayout mainWalletOcLinMain;
    private String inviteCode;
    private String exchangeUid;
    private MeFragmentPresnterImp invitationPresnterImp;
    // the fragment initialization parameters,e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    public static MeFragment newInstance() {
        MeFragment fragment = new MeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, "");
        args.putString(ARG_PARAM2, "");
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarId.getHeight());
        layoutParams.topMargin = StatusBarUtil.getStatusBarHeight(MyApplication.mContext);
        statusBarId.setLayoutParams(layoutParams);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        //todo 二维码 导入私钥回调
        if (requestCode == AppConstants.ME_REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(Intents.Scan.RESULT);
                LogUtil.error("ramon", "result: " + content);
                if (TextUtils.isEmpty(content)) {
                    toast(getResources().getString(R.string.text_invalid_qrcode));
                    return;
                }
                switch (QRUtils.scanType(content)) {
                    case 1:
                        //转账地址
                        String scanResult = QRUtils.getContentString(content, 1);
                        String[] split = scanResult.split("_");  // split[0] 数量  split[1] 钱包地址 split[2] 币种
                        String sum = split[0];
                        String address = split[1];
                        IntentUtils.JumpToHaveOne(ZhuanZhangActivity.class, AppConstants.SCAN_ADDRESS, addHead(address));
                        break;
                    case 2:
                        //地址
                        String address2 = QRUtils.getContentString(content, 2);
                        String currentSaveAddressList = UserUtils.getCurrentSaveAddressList();
                        Intent intent = new Intent(getActivity(), AddAddressActivity.class);
                        Bundle bundle = new Bundle();
                        if (!currentSaveAddressList.isEmpty()) {
                            SaveAddressInfo saveAddressInfo = GsonUtil.GsonToBean(currentSaveAddressList, SaveAddressInfo.class);
                            bundle.putSerializable(AppConstants.ITEM_OBJ, saveAddressInfo);
                        }
                        bundle.putSerializable(AppConstants.ADDRESSINFO, addHead(address2));
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    case 3:
                        //私钥
                        if (QRUtils.scanType(content) == 3) {
                            //解析私钥，填入私钥
                            String resPk = QRUtils.getContentString(content, 3);
                            IntentUtils.JumpToHaveOne(ImportWalletActivity.class, AppConstants.RESPK, resPk);
                        }

                        break;

                    default:
                        toast(getResources().getString(R.string.text_invalid_qrcode));
                        break;
                }
            }
        }
    }


    @OnClick({R.id.security_center_layout,
            R.id.address_layout,
            R.id.customer_server,
            R.id.about_us_layout,
            R.id.tv_inv_friend,
            R.id.iv_message,
            R.id.tv_scan,
            R.id.tv_my_team,
            R.id.user_name,
            R.id.user_address,
            R.id.tv_bind_romeex,
            R.id.user_inv_code,
            R.id.user_inv_copy,
            R.id.layout_inv,
            R.id.setting_layout,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_name:
                //钱包管理
                startActivity(new Intent(activity, WalletManagerActivity.class));
                break;
            case R.id.user_address:
                //地址管理
                copyString(userAddress.getText().toString().trim());
                break;
            case R.id.security_center_layout:
                //安全中心
                IntentUtils.JumpTo(SecurityCenterActivity.class);
                break;
            case R.id.tv_bind_romeex:
                //绑定交易所
                IntentUtils.JumpToHaveOne(BindRomeexActivity.class, AppConstants.EXCHANGEUID, exchangeUid);
//                IntentUtils.JumpToHaveOne(BindRomeexActivitybackup.class, AppConstants.EXCHANGEUID, exchangeUid);
                break;
            case R.id.tv_inv_friend:
                //邀请好友
                IntentUtils.JumpToHaveOne(InvitationActivity.class, AppConstants.INTENT_INVITATION_CODE, inviteCode);
                break;
            case R.id.tv_my_team:
                //我的团队
//                toast(getResources().getString(R.string.text_not_open), Gravity.CENTER);
                IntentUtils.JumpTo(MyTeamActivity.class);
                break;
            case R.id.address_layout:
                //地址薄
                IntentUtils.JumpToHaveOneInt(AddressActivity.class, "isSelect", -1);
                break;
            case R.id.customer_server:
                //联系客服
                showLoading("");
                invitationPresnterImp.requestUserRegisterKF();
                break;
            case R.id.about_us_layout:
                //关于我们
                IntentUtils.JumpTo(AboutUsActivity.class);
                break;
            case R.id.setting_layout:
                //设置
                IntentUtils.JumpTo(SettingActivity.class);
                break;
            case R.id.iv_message:
                //消息
                IntentUtils.JumpTo(MessageActivity.class);
                break;
            case R.id.tv_scan:
                //扫描
                Intent intent = new Intent(getActivity(), ScanActivity.class);
                startActivityForResult(intent, AppConstants.ME_REQUEST_CODE_SCAN);
                break;
            case R.id.user_inv_copy:
                //二维码
                layoutInv.setVisibility(View.VISIBLE);
                ImagesUtil.createQrCodeImg(QRUtils.type4 + inviteCode, qr_code_inv, 500);
                break;
            case R.id.user_inv_code:
                //复制二维码
                if (!TextUtils.isEmpty(inviteCode)) {
                    copyString(inviteCode);
                }
                break;
            case R.id.layout_inv:
                //复制二维码
                layoutInv.setVisibility(View.GONE);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        invitationPresnterImp = new MeFragmentPresnterImp(getActivity(), this);
        invitationPresnterImp.requestHomeInfo();
    }

    @Override
    public void success(UserInfoBean data) {
        if (null != data && isAdded()) {
            inviteCode = data.getInviteCode();
            exchangeUid = data.getExchangeUid();
            user_inv_code.setText(MessageFormat.format("{0} {1}", getString(R.string.text_me_inv_code), inviteCode));
            if (data.getMinnerLevel() == 1) {
                icon_kz.setVisibility(View.VISIBLE);
                userLevel.setVisibility(View.VISIBLE);
            }
            if (UserUtils.getCurrentUserExchangeUid().isEmpty()) {
                UserUtils.setCurrentUserExchangeUid(exchangeUid);
            }
            LogUtil.error("MeFragment", data.toString());
        }
    }

    @Override
    public void responseUserRegisterKFSuccess(UserRegisterKFBean data) {
        dismissLoading();
        if (data != null && isAdded()) {
            String kfToken = data.getKfToken();
            if (kfToken.isEmpty()) {
                toast(getResources().getString(R.string.get_chat_server_failed));
                return;
            }
            //未登录，需要登录后，再进入会话界面
            LogUtil.error("xx", "UserUtils.getCurrentUserAddress():" + UserUtils.getCurrentUserAddress());
            LogUtil.error("xx", "kfToken:" + kfToken);
            if (ChatClient.getInstance().isLoggedInBefore()) {
                //已经登录，可以直接进入会话界面
                Intent intent = new IntentBuilder(getActivity())
                        //获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“IM服务号”
                        .setServiceIMNumber("kefuchannelimid_234910")
                        .build();
                startActivity(intent);
            } else {
                //未登录，需要登录后，再进入会话界面
                ChatClient.getInstance().login(UserUtils.getCurrentUserAddress(), kfToken, new Callback() {
                    @Override
                    public void onSuccess() {
                        if (isAdded()) {
                            Intent intent = new IntentBuilder(getActivity())
                                    //获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“IM服务号”
                                    .setServiceIMNumber("kefuchannelimid_234910")
                                    .build();
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onError(int code, String error) {
                        LogUtil.error("xx", "error:" + error);
                        if (code == 200 && error.equals("User is already login")) {
                            Intent intent = new IntentBuilder(getActivity())
                                    //获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“IM服务号”
                                    .setServiceIMNumber("kefuchannelimid_234910")
                                    .build();
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                        LogUtil.error("xx", "status:" + status);
                    }
                });
            }

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        WalletInfo user = UserUtils.getCurrentUser();
        if (null != user) {
            userName.setText(user.getUserName());
            userAddress.setText(StringTool.addHead(user.getAddress()));
        }
    }

    @Override
    public void setFailure() {
        dismissLoading();
    }
}
